package commMqtt

import "sync"

var (
	mutex   sync.Mutex
	clients sync.Map
)

type mqttManager struct {
	mutex   sync.Mutex
	clients sync.Map
}

func (e *mqttManager) hasClient(clientId string) bool {
	mutex.Lock()
	defer mutex.Unlock()

	client, ok := clients.Load(clientId)
	if !ok || client == nil {
		return false
	}

	return true
}

func (e *mqttManager) getClient(clientId string) *MqttClient {
	mutex.Lock()
	defer mutex.Unlock()

	client, ok := clients.Load(clientId)
	if !ok || client == nil {
		return nil
	}

	return client.(*MqttClient)
}

func (e *mqttManager) newClient(clientId string) *MqttClient {
	mutex.Lock()
	defer mutex.Unlock()

	if clientId == "" {
		return nil
	}

	val, ok := clients.Load(clientId)
	if !ok || val == nil {
		val = &MqttClient{}
	}
	client := val.(*MqttClient)

	// 初始化配置参数
	options := make(map[string]interface{})
	client.initDefaultOption()
	client.clientId = clientId
	client.SetOption(options)

	clients.Store(clientId, val)
	return client
}

func (e *mqttManager) delClient(clientId string) {
	mutex.Lock()
	defer mutex.Unlock()

	val, ok := clients.Load(clientId)
	if !ok {
		return
	}
	if val == nil {
		clients.Delete(clientId)
		return
	}

	client := val.(*MqttClient)
	if client.IsConnected() {
		client.Disconnect()
	}

	clients.Delete(clientId)
}

func (e *mqttManager) keys() map[string]interface{} {
	mutex.Lock()
	defer mutex.Unlock()

	keys := make(map[string]interface{})
	clients.Range(func(clientId, value interface{}) bool {
		keys[clientId.(string)] = nil
		return true
	})

	return keys
}
